//
//  MBDPostListViewModel.swift
//  MasterBoy
//
//  Created by kyson on 2023/4/21.
//

import Foundation
import SwiftyJSON

import UIKit
import YYText
import Alamofire

class MBDPostCellModel : MBDCommonCellModel {
    
    var titlelayout : YYTextLayout!
    var statusLayout : YYTextLayout!
    var subtitlelayout : YYTextLayout!
    var cellHeight : CGFloat!
    
    static let topMargin :CGFloat = 15
    static let leftMargin :CGFloat = 15
    static let uploaderAvatarHeight :CGFloat = 32
    static let marginBetweenAvatarAndTitle :CGFloat = 10
    static let marginBetweenTitleAndSubtitle :CGFloat = 8
    static let marginSubtitleLeft :CGFloat = 15
    static let marginSubtitleRight :CGFloat = 15
    //保持 16:9
    static let groupCoverHeight : CGFloat =  (UIScreen.main.bounds.width - MBDPostCellModel.leftMargin * 2 ) * MBDPickerConfig.ratioGroupLogoHeightWidth

    static let groupCoverMarginTop :CGFloat = 6
    static let groupCoverMarginBottom :CGFloat = 6
    
    var groupDetail : MBDGroupDetailModel! {
        didSet {
            self.title = self.groupDetail.groupName
            
            let gpdsc = self.groupDetail.groupDesc.replacingOccurrences(of: "\n", with: "")
            //todo:这里有个问题，替换空格不起作用
            var gpdscWithoutSpace = gpdsc.replacingOccurrences(of: " ", with: "")
            let gpdscWithoutTab = gpdscWithoutSpace.replacingOccurrences(of: "\t", with: "")

            self.subtitle = gpdscWithoutTab
            self.groupCoverURL = MBDPath2URLUtils.wrapGroupLogoURL(path: self.groupDetail.groupLogo)
            
            self.status = self.groupDetail.groupStatus
        }
    }
    
    var title: String? {
        didSet {
            
            let titleAttributeString = NSMutableAttributedString(string: self.title ?? "")
            titleAttributeString.yy_font = UIFont.boldSystemFont(ofSize: 18)
            titleAttributeString.setDynamicTextColor()
            
            let titlecontainer = YYTextContainer()
            let titleWidth = CGRectGetWidth(UIScreen.main.bounds) - 15 - 60 - 15 - 15
            titlecontainer.size = CGSizeMake(titleWidth , CGFLOAT_MAX)
            titlecontainer.maximumNumberOfRows = 1
            
            self.titlelayout = YYTextLayout(container: titlecontainer, text: titleAttributeString)
            self.updateCellHeight()
        }
    }
    
    var status: MBDGroupStatus? {
        
        didSet {
            
            var sts : String
            if self.status == .under {
                sts = "审核中"
            } else if self.status == .reject {
                sts = "被拒绝"
            } else {
                sts = "审核通过"
            }
            
            let statusAttributeString = NSMutableAttributedString(string: sts)
            statusAttributeString.yy_insertString("  ", at: 0)
            statusAttributeString.yy_appendString("  ")
            statusAttributeString.yy_font = UIFont.systemFont(ofSize: 12)
//            statusAttributeString.yy_lineSpacing = 10;
//            statusAttributeString.yy_paragraphSpacing = 10;

            let border = YYTextBorder()
            border.strokeWidth = 1.8
            border.cornerRadius = 100
            border.lineJoin = .bevel
//            border.insets = UIEdgeInsets(top: -2, left: -5.5, bottom: -2, right: -8)
            
            if self.status == .under {
                border.fillColor = UIColor.lightGray
                border.strokeColor = UIColor.white
                
                statusAttributeString.yy_color = .white
                
            } else if self.status == .reject {
                border.fillColor = UIColor.red
                border.strokeColor = .white
                
                statusAttributeString.yy_color = .white

            } else {
                border.fillColor = UIColor(colorHex: 0x0ec468)
//                border.strokeColor = UIColor(colorHex: 0x333333)
//                
                statusAttributeString.yy_color = .white

            }
            
            statusAttributeString.yy_textBackgroundBorder = border
            
            let statusContainer = YYTextContainer()
            let statusWidth = CGRectGetWidth(UIScreen.main.bounds) - 15 - 60 - 15 - 15
            statusContainer.size = CGSizeMake(statusWidth , CGFLOAT_MAX)
            statusContainer.maximumNumberOfRows = 1
            
            self.statusLayout = YYTextLayout(container: statusContainer, text: statusAttributeString)
            
        }
    }
    
    var subtitle: String? {
        didSet {
            
            let subtitleAttributeString = NSMutableAttributedString(string: self.subtitle ?? "")
            subtitleAttributeString.yy_font = UIFont.systemFont(ofSize: 14)
            subtitleAttributeString.yy_lineSpacing = 4
            subtitleAttributeString.setDynamicTextColor()
            
            let subtitleContainer = YYTextContainer()
            let subtitleWidth = CGRectGetWidth(UIScreen.main.bounds) - MBDPostCellModel.marginSubtitleLeft - MBDPostCellModel.marginSubtitleRight
            subtitleContainer.size = CGSizeMake(subtitleWidth , CGFLOAT_MAX)
            subtitleContainer.maximumNumberOfRows = 3
            
            self.subtitlelayout = YYTextLayout(container: subtitleContainer, text: subtitleAttributeString)
            
            self.updateCellHeight()
        }
    }
    
    var groupCoverURL : String? {
        didSet {
            self.updateCellHeight()
        }
    }

    func updateCellHeight(){
        var cellHeight = MBDPostCellModel.topMargin
        
        if let tl = self.titlelayout {
            cellHeight += tl.textBoundingSize.height
            
            cellHeight += MBDPostCellModel.marginBetweenAvatarAndTitle
        }
        
        if let stl = self.subtitlelayout {
            cellHeight += stl.textBoundingSize.height
            
            cellHeight += MBDPostCellModel.marginBetweenTitleAndSubtitle
        }
        
        if let cover = self.groupCoverURL {
            cellHeight += MBDPostCellModel.groupCoverMarginTop
            cellHeight += MBDPostCellModel.groupCoverHeight
            cellHeight += MBDPostCellModel.groupCoverMarginBottom
        }
                
        cellHeight += 10
        
        self.cellHeight = cellHeight
    }
    
}

class MBDPostListViewModel : NSObject {
    public static let pageSize = 10

    var cellModels : Array<MBDPostCellModel>?
    
    override init() {
        super.init()
        cellModels = Array()
        
    }
    
    func doRequest(pageNum:Int = 1, completion : @escaping (_ error : NSError?,_ result : Array<MBDPostCellModel>?,_ totalPage : Int)->()) {
        
        MBDHttpClient.shared.request("/user/group/listPage",parameters: ["pageNum":String(pageNum)],encoding: URLEncoding.default).httpClientResponse { error, response in
            
            if nil != error {
                completion(error,nil,0)
            } else {
                let rawDict = response?.rawDict as! Dictionary<String,Any>
                let rawRows = rawDict["data"]
                let totalPage = rawDict["totalPage"] as! Int
                

                if rawRows is Array<Any> {
                    let rows = rawRows as! Array<Any>
                    
                    var multiRows = Array<MBDPostCellModel>()
                    for row in rows {
                        let item = MBDGroupDetailModel(JSON(rawValue: row) ?? JSON(NSObject()))
                        let cellModel = MBDPostCellModel()
                        cellModel.groupDetail = item
                        multiRows.append(cellModel)
                        
                    }
                    completion(nil,multiRows,totalPage)
                } else {
                    completion(error,nil,0)
                }
            }
        }
    }
    
    func deleteGroupRequest(groupId:String, completion : @escaping (_ result:Bool)->()) {
        
        MBDHttpClient.shared.request("/group/delete",method: .delete,parameters: ["groupId":groupId]).httpClientResponse { error, response in
            if nil != error{
                completion(false)
            } else {
                completion(true)
            }
        }
    }
}
